/**
 * 监听交易，筛选出ERC20代币转账交易，解析交易详情
 */

import { ethers } from "ethers";

const ALCHEMY_MAINNET_WSSURL = 'wss://eth-mainnet.g.alchemy.com/v2/mkM5-GVJCs00ghRsjT7aU';
const provider = new ethers.WebSocketProvider(ALCHEMY_MAINNET_WSSURL)

const iface = new ethers.Interface([
    "function transfer(address, uint256) public returns(bool)"
])
const selector = iface.getFunction("transfer").selector

function handleBigInt(key, value) {
    if (typeof value === "bigint") {
        return value.toString() + "n"; // or simply return value.toString();
    }
return value;
}

provider.on('pending', async (txHash) =>{
    const tx = await provider.getTransaction(txHash)
    if(tx != null && tx.data.indexOf(selector) != -1){
        console.log(tx)
        console.log(`打印解码交易详情:${JSON.stringify(iface.parseTransaction(tx), handleBigInt, 2)}`)
        console.log(`转账目标地址:${iface.parseTransaction(tx).args[0]}`)
        console.log(`转账金额:${iface.parseTransaction(tx).args[1]}`)
        provider.removeListener('pending', this)
    }

})
